package shop.gateway.handler;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import shop.common.core.Result;

@Slf4j
@Configuration
public class GatewayExceptionHandler implements ErrorWebExceptionHandler
{

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex)
    {
        ServerHttpResponse response = exchange.getResponse();

        log.error("[ 网关异常处理 ], 请求路径: {}, 异常信息: {}", exchange.getRequest().getPath(), ex.getMessage());

        Result result = shop.common.core.Result.fail().data(ex.getMessage());
        DataBuffer dataBuffer = null;
        try {
            dataBuffer = response.bufferFactory().wrap(new ObjectMapper().writeValueAsBytes(result));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return response.writeWith(Mono.just(dataBuffer));
    }
}